package Server;

import java.io.File;
import java.io.IOException;
import java.rmi.RemoteException;

import common.ClientInterface;

public class mainServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String man = ("Use:\n" +
				"server.jar r|s ADDRESS PORT [FILE] \n"+
				"r - RMI communication with the clients\n" +
				"s - socket communication with the clients\n" +
				"ADDRESS, PORT - IP address and TCP port to bind the server\n" + 
				"FILE - map file path\n" +
				"d - restore data from DB");

		Game game = null;
		ClientInterface myClient = null;
		
		try{
			if (args.length > 4){
				if (args[4].equals("d")){
					game = Game.getGame(true);
				} else {
					System.out.println("Parametro sconosciuto: " + args[4]);
					System.out.println(man);
					System.exit(1);
				}
			} else{
					game = Game.getGame();
			}
		} catch (RemoteException e){
			System.out.println("Errore generico\n");
		}
		
		try{
			if (args[0].equals("r")){
				myClient = new RmiGame();
			}
			else if (args[0].equals("s")){
				myClient = new SocketGame();
			}
			else {
				System.out.println("Parametro sconosciuto: "+args[0]);
				System.out.println(man);
				System.exit(1);
			}
		} catch (ArrayIndexOutOfBoundsException e){
			System.out.println(man);
			System.exit(1);
		} catch (IOException e){
			System.out.println("Errore generico\n");
		}
		
		game.setClient(myClient);
		try{
			if (args.length > 3){
				File f = new File(args[3]);
				if (f.isFile() && f.canRead()){
					game.useMapData(f.getCanonicalPath());
				}
			}
		} catch (IOException e){
			System.out.println("Parametro sconosciuto: " + args[3]);
			System.out.println(man);
			System.exit(1);
		}

	}

}
